Middleware Pattern
Expressでも使われてる
/miyamonz/middleware パターンに対する考察
https://gyazo.com/d99f087bca81f2b12d448dc447d6e155 https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/index/_static/request-delegate-pipeline.png?view=aspnetcore-8.0
継続っぽいmrsekut.icon
gpt-5.icon
リクエストや処理のパイプライン途中に共通処理を差し込むための設計パターン
主処理(ビジネスロジック)から横断的関心事を分離することが目的。
基本構造
処理は「前処理 → 次の処理 → 後処理」という形で**連鎖(チェーン)**する。
code:text
Request
↓
Middleware A
↓
Middleware B
↓
Middleware C
↓
Handler(本処理)
各 Middleware は次を呼ぶ責務を持つ。
擬似コード例(JavaScript)
code:js
const middlewareA = (ctx, next) => {
// 前処理
console.log("A before");
next();
// 後処理
console.log("A after");
};
const middlewareB = (ctx, next) => {
console.log("B before");
next();
console.log("B after");
};
const handler = (ctx) => {
console.log("handler");
};
実行順序は以下になる:
code:text
A before
B before
handler
B after
A after